{% extends "members/base.html" %}

{% block title %}量表详情{% endblock %}

{% block extra_css %}
<style>
    .detail-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem;
        border-radius: 10px;
        margin-bottom: 2rem;
    }
    .info-card {
        border: 1px solid #e9ecef;
        border-radius: 10px;
        padding: 1.5rem;
        background: white;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
    }
    .stat-item {
        text-align: center;
        padding: 1rem;
        border-radius: 8px;
        background: #f8f9fa;
        margin-bottom: 1rem;
    }
    .stat-value {
        font-size: 2rem;
        font-weight: bold;
        color: #007bff;
        margin-bottom: 0.5rem;
    }
    .stat-label {
        color: #6c757d;
        font-size: 0.9rem;
    }
    .question-preview {
        max-height: 400px;
        overflow-y: auto;
        border: 1px solid #e9ecef;
        border-radius: 8px;
        padding: 1rem;
    }
    .question-item {
        border-bottom: 1px solid #f1f3f4;
        padding: 1rem 0;
    }
    .question-item:last-child {
        border-bottom: none;
    }
    .option-item {
        padding: 0.25rem 0;
        margin-left: 1rem;
        color: #6c757d;
    }
    .action-buttons {
        position: sticky;
        bottom: 0;
        background: white;
        padding: 1rem 0;
        border-top: 1px solid #e9ecef;
        margin-top: 2rem;
    }
    .loading-spinner {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 200px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 加载状态 -->
    <div id="loading-container" class="loading-spinner">
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mt-2">正在加载量表详情...</p>
        </div>
    </div>

    <!-- 量表详情内容 -->
    <div id="scale-content" style="display: none;">
        <!-- 页面标题 -->
        <div class="detail-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h2 class="mb-2" id="scale-title">量表详情</h2>
                    <p class="mb-0" id="scale-subtitle"></p>
                </div>
                <div class="col-md-4 text-end">
                    <div class="d-flex align-items-center justify-content-end">
                        <span class="badge bg-light text-dark me-2" id="scale-status"></span>
                        <span class="text-white-50" id="scale-id"></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- 基本信息 -->
            <div class="col-md-8">
                <div class="info-card">
                    <h5 class="mb-3"><i class="bi bi-info-circle me-2"></i>基本信息</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="30%"><strong>量表名称:</strong></td>
                                    <td id="info-title">-</td>
                                </tr>
                                <tr>
                                    <td><strong>分类:</strong></td>
                                    <td id="info-category">-</td>
                                </tr>
                                <tr>
                                    <td><strong>题目数量:</strong></td>
                                    <td id="info-question-count">-</td>
                                </tr>
                                <tr>
                                    <td><strong>预估时间:</strong></td>
                                    <td id="info-estimated-time">-</td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <td width="30%"><strong>创建时间:</strong></td>
                                    <td id="info-created-at">-</td>
                                </tr>
                                <tr>
                                    <td><strong>更新时间:</strong></td>
                                    <td id="info-updated-at">-</td>
                                </tr>
                                <tr>
                                    <td><strong>版本:</strong></td>
                                    <td id="info-version">-</td>
                                </tr>
                                <tr>
                                    <td><strong>作者:</strong></td>
                                    <td id="info-author">-</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    <div class="mt-3">
                        <strong>描述:</strong>
                        <p class="text-muted mt-2" id="info-description">-</p>
                    </div>
                    <div class="mt-3" id="instruction-section" style="display: none;">
                        <strong>测试说明:</strong>
                        <div class="alert alert-info mt-2" id="info-instruction"></div>
                    </div>
                </div>

                <!-- 题目预览 -->
                <div class="info-card">
                    <h5 class="mb-3"><i class="bi bi-list-ol me-2"></i>题目预览</h5>
                    <div id="questions-container">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2">正在加载题目...</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 统计信息 -->
            <div class="col-md-4">
                <div class="info-card">
                    <h5 class="mb-3"><i class="bi bi-bar-chart me-2"></i>统计信息</h5>
                    <div class="row">
                        <div class="col-12">
                            <div class="stat-item">
                                <div class="stat-value" id="stat-usage-count">-</div>
                                <div class="stat-label">使用次数</div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="stat-item">
                                <div class="stat-value" id="stat-completed-count">-</div>
                                <div class="stat-label">完成次数</div>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="stat-item">
                                <div class="stat-value" id="stat-completion-rate">-</div>
                                <div class="stat-label">完成率</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 最近测评记录 -->
                <div class="info-card">
                    <h5 class="mb-3"><i class="bi bi-clock-history me-2"></i>最近测评记录</h5>
                    <div id="recent-assessments">
                        <div class="text-center py-4">
                            <div class="spinner-border text-primary" role="status"></div>
                            <p class="mt-2">正在加载记录...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <div class="d-flex gap-2">
                <a href="{{ url_for('members.my_scales') }}" class="btn btn-secondary">
                    <i class="bi bi-arrow-left me-1"></i>返回我的量表
                </a>
                <button type="button" class="btn btn-primary" id="edit-btn" style="display: none;">
                    <i class="bi bi-pencil me-1"></i>编辑量表
                </button>
                <button type="button" class="btn btn-info" id="preview-btn">
                    <i class="bi bi-eye me-1"></i>预览量表
                </button>
                <button type="button" class="btn btn-success" id="publish-btn" style="display: none;">
                    <i class="bi bi-upload me-1"></i>发布量表
                </button>
                <button type="button" class="btn btn-warning" id="archive-btn" style="display: none;">
                    <i class="bi bi-archive me-1"></i>归档量表
                </button>
                <button type="button" class="btn btn-outline-success" id="assessment-link-btn" style="display: none;">
                    <i class="bi bi-link-45deg me-1"></i>测评链接
                </button>
                <button type="button" class="btn btn-outline-info" id="qr-code-btn" style="display: none;">
                    <i class="bi bi-qr-code me-1"></i>生成二维码
                </button>
            </div>
        </div>
    </div>

    <!-- 错误状态 -->
    <div id="error-container" style="display: none;">
        <div class="alert alert-danger text-center">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <span id="error-message">加载失败，请稍后重试</span>
        </div>
        <div class="text-center">
            <a href="{{ url_for('members.my_scales') }}" class="btn btn-secondary">
                <i class="bi bi-arrow-left me-1"></i>返回我的量表
            </a>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
const scaleId = {{ scale_id|tojson }};
let scaleData = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadScaleDetail();
});

// 加载量表详情
function loadScaleDetail() {
    apiRequest(`/api/scales/${scaleId}`)
        .then(response => {
            if (response.success) {
                scaleData = response.data;
                renderScaleDetail(scaleData);
                loadQuestions();
                loadRecentAssessments();
                setupActionButtons();
                
                // 显示内容，隐藏加载状态
                document.getElementById('loading-container').style.display = 'none';
                document.getElementById('scale-content').style.display = 'block';
            } else {
                showError(response.message || '量表不存在或无权访问');
            }
        })
        .catch(error => {
            console.error('加载量表详情失败:', error);
            showError('加载失败，请稍后重试');
        });
}

// 渲染量表详情
function renderScaleDetail(scale) {
    // 页面标题
    document.getElementById('scale-title').textContent = scale.title;
    document.getElementById('scale-subtitle').textContent = scale.subtitle || scale.description;
    document.getElementById('scale-status').textContent = getStatusText(scale.status);
    document.getElementById('scale-status').className = `badge ${getStatusClass(scale.status)}`;
    document.getElementById('scale-id').textContent = `ID: ${scale.id}`;
    
    // 基本信息
    document.getElementById('info-title').textContent = scale.title;
    document.getElementById('info-category').textContent = scale.category_name || '未分类';
    document.getElementById('info-question-count').textContent = `${scale.question_count || 0} 题`;
    document.getElementById('info-estimated-time').textContent = scale.estimated_time ? `${scale.estimated_time} 分钟` : '-';
    document.getElementById('info-created-at').textContent = formatDateTime(scale.created_at);
    document.getElementById('info-updated-at').textContent = formatDateTime(scale.updated_at);
    document.getElementById('info-version').textContent = scale.version || '1.0';
    document.getElementById('info-author').textContent = scale.author || '-';
    document.getElementById('info-description').textContent = scale.description || '-';
    
    // 测试说明
    if (scale.instruction) {
        document.getElementById('instruction-section').style.display = 'block';
        document.getElementById('info-instruction').textContent = scale.instruction;
    }
    
    // 统计信息
    document.getElementById('stat-usage-count').textContent = scale.usage_count || 0;
    document.getElementById('stat-completed-count').textContent = scale.completed_count || 0;
    
    const completionRate = scale.usage_count > 0 ? 
        Math.round((scale.completed_count || 0) / scale.usage_count * 100) : 0;
    document.getElementById('stat-completion-rate').textContent = `${completionRate}%`;
}

// 加载题目
function loadQuestions() {
    const container = document.getElementById('questions-container');
    
    if (!scaleData.questions || scaleData.questions.length === 0) {
        container.innerHTML = '<p class="text-muted text-center py-4">该量表暂无题目</p>';
        return;
    }
    
    let html = '<div class="question-preview">';
    
    // 只显示前5个题目
    const questionsToShow = scaleData.questions.slice(0, 5);
    
    questionsToShow.forEach((question, index) => {
        html += `
            <div class="question-item">
                <div class="fw-bold mb-2">${question.question_number || (index + 1)}. ${escapeHtml(question.question_text)}</div>
                <div class="small text-muted mb-2">类型: ${getQuestionTypeText(question.question_type)}</div>
        `;
        
        if (question.options && question.options.length > 0) {
            question.options.forEach(option => {
                html += `<div class="option-item">• ${escapeHtml(option.option_text)}</div>`;
            });
        }
        
        html += '</div>';
    });
    
    if (scaleData.questions.length > 5) {
        html += `<div class="text-center text-muted py-3">... 还有 ${scaleData.questions.length - 5} 个题目</div>`;
    }
    
    html += '</div>';
    container.innerHTML = html;
}

// 加载最近测评记录
function loadRecentAssessments() {
    const container = document.getElementById('recent-assessments');
    
    // 这里应该调用API获取该量表的测评记录
    // 暂时显示占位内容
    container.innerHTML = '<p class="text-muted text-center py-4">暂无测评记录</p>';
}

// 设置操作按钮
function setupActionButtons() {
    if (!scaleData) return;
    
    // 编辑按钮 - 只有自己创建的量表才能编辑
    if (scaleData.can_edit) {
        document.getElementById('edit-btn').style.display = 'inline-block';
        document.getElementById('edit-btn').onclick = () => {
            window.location.href = `/members/scale-creator?id=${scaleId}`;
        };
    }
    
    // 预览按钮
    document.getElementById('preview-btn').onclick = () => {
        window.open(`/scales/${scaleId}/preview`, '_blank');
    };
    
    // 发布/归档按钮
    if (scaleData.can_edit) {
        if (scaleData.status === 'DRAFT') {
            document.getElementById('publish-btn').style.display = 'inline-block';
            document.getElementById('publish-btn').onclick = () => publishScale();
        } else if (scaleData.status === 'PUBLISHED') {
            document.getElementById('archive-btn').style.display = 'inline-block';
            document.getElementById('archive-btn').onclick = () => archiveScale();
        }
    }
    
    // 测评链接和二维码按钮（对所有已发布的量表都可见）
    if (scaleData.status === 'PUBLISHED') {
        document.getElementById('assessment-link-btn').style.display = 'inline-block';
        document.getElementById('assessment-link-btn').onclick = () => showAssessmentLink();
        
        document.getElementById('qr-code-btn').style.display = 'inline-block';
        document.getElementById('qr-code-btn').onclick = () => generateQRCode();
    }
}

// 发布量表
function publishScale() {
    if (!confirm('确定要发布这个量表吗？发布后将对所有用户可见。')) {
        return;
    }
    
    apiRequest(`/api/scales/${scaleId}/publish`, {
        method: 'POST'
    })
    .then(response => {
        if (response.success) {
            alert('量表发布成功！');
            location.reload();
        } else {
            alert('发布失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('发布量表失败:', error);
        alert('发布失败，请稍后重试');
    });
}

// 归档量表
function archiveScale() {
    if (!confirm('确定要归档这个量表吗？归档后将不再对用户可见。')) {
        return;
    }
    
    apiRequest(`/api/scales/${scaleId}/archive`, {
        method: 'POST'
    })
    .then(response => {
        if (response.success) {
            alert('量表归档成功！');
            location.reload();
        } else {
            alert('归档失败: ' + response.message);
        }
    })
    .catch(error => {
        console.error('归档量表失败:', error);
        alert('归档失败，请稍后重试');
    });
}

// 显示测评链接
function showAssessmentLink() {
    const assessmentUrl = `${window.location.origin}/scales/${scaleId}/assessment`;
    
    // 创建模态框显示链接
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">测评链接</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>用户可以通过以下链接进行测评：</p>
                    <div class="input-group">
                        <input type="text" class="form-control" value="${assessmentUrl}" readonly id="assessment-url">
                        <button class="btn btn-outline-secondary" type="button" onclick="copyAssessmentLink()">复制</button>
                    </div>
                    <div class="mt-3">
                        <small class="text-muted">此链接可以分享给需要进行测评的用户</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="window.open('${assessmentUrl}', '_blank')">预览测评页面</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
    
    // 模态框关闭后移除元素
    modal.addEventListener('hidden.bs.modal', () => {
        document.body.removeChild(modal);
    });
}

// 复制测评链接
function copyAssessmentLink() {
    const input = document.getElementById('assessment-url');
    input.select();
    document.execCommand('copy');
    alert('链接已复制到剪贴板！');
}

// 生成二维码
function generateQRCode() {
    const assessmentUrl = `${window.location.origin}/scales/${scaleId}/assessment`;
    
    // 使用在线二维码生成服务
    const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(assessmentUrl)}`;
    
    // 创建模态框显示二维码
    const modal = document.createElement('div');
    modal.className = 'modal fade';
    modal.innerHTML = `
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">测评二维码</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center">
                    <p>扫描二维码进行测评：</p>
                    <img src="${qrCodeUrl}" alt="测评二维码" class="img-fluid mb-3" style="max-width: 200px;">
                    <div class="small text-muted">
                        <p>用户可以使用手机扫描此二维码直接进入测评页面</p>
                        <p class="mb-0">链接：${assessmentUrl}</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="downloadQRCode('${qrCodeUrl}')">下载二维码</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    const bsModal = new bootstrap.Modal(modal);
    bsModal.show();
    
    // 模态框关闭后移除元素
    modal.addEventListener('hidden.bs.modal', () => {
        document.body.removeChild(modal);
    });
}

// 下载二维码
function downloadQRCode(qrCodeUrl) {
    const link = document.createElement('a');
    link.href = qrCodeUrl;
    link.download = `scale-${scaleId}-qrcode.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 显示错误
function showError(message) {
    document.getElementById('loading-container').style.display = 'none';
    document.getElementById('scale-content').style.display = 'none';
    document.getElementById('error-message').textContent = message;
    document.getElementById('error-container').style.display = 'block';
}

// 工具函数
function getStatusText(status) {
    const statusMap = {
        'DRAFT': '草稿',
        'PUBLISHED': '已发布',
        'ARCHIVED': '已归档'
    };
    return statusMap[status] || status;
}

function getStatusClass(status) {
    const classMap = {
        'DRAFT': 'bg-warning text-dark',
        'PUBLISHED': 'bg-success',
        'ARCHIVED': 'bg-secondary'
    };
    return classMap[status] || 'bg-light text-dark';
}

function getQuestionTypeText(type) {
    const typeMap = {
        'single_choice': '单选题',
        'multiple_choice': '多选题',
        'text': '文本题',
        'scale': '量表题'
    };
    return typeMap[type] || type;
}

function formatDateTime(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// API请求函数已在base.html中定义，无需重复定义
</script>
{% endblock %}